package org.jeecg.modules.demo.gmslopedata.controller;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@Configuration
@EnableAsync
public class ThreadConfig {

    // 线程池核心参数（需根据业务压测调整）
    private static final int CORE_POOL_SIZE = 5;
    private static final int MAX_POOL_SIZE = 10;
    private static final int KEEP_ALIVE_TIME = 30;
    private TimeUnit unit = TimeUnit.SECONDS;
    private BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100);
    private static final RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.DiscardPolicy();
    // 使用CallerRunsPolicy替代DiscardPolicy

    private ThreadFactory threadFactory = new CustomThreadFactory("gm-data-thread-");

    @Bean("gmDataThreadPool")
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setKeepAliveSeconds(KEEP_ALIVE_TIME);
        executor.setQueueCapacity(workQueue.size());
//        executor.setThreadNamePrefix(threadFactory.toString());
        // 使用内置线程工厂
        executor.setThreadNamePrefix("gm-data-thread-");
//        executor.setRejectedExecutionHandler(HANDLER);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    // 自定义线程工厂（规范线程命名）
    static class CustomThreadFactory implements ThreadFactory {
        private final String prefix;
        private final AtomicInteger threadNum = new AtomicInteger(0);

        CustomThreadFactory(String prefix) {
            this.prefix = prefix;
        }

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, prefix + threadNum.getAndIncrement());
            thread.setDaemon(false); // 非守护线程（保证任务执行完再退出）
            return thread;
        }
    }
}



